package ml2;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import nom.tam.fits.BasicHDU;
import nom.tam.fits.BinaryTableHDU;
import nom.tam.fits.Fits;
import nom.tam.fits.FitsException;
import nom.tam.fits.FitsFactory;
import nom.tam.util.BufferedDataOutputStream;



public class Utils {
    public static void saveFits(double[][] magnificationArray, double[][] shootingArray,StarBag starBag, String filename, 
	    String[] keys, String[] values,String[] comments){
	try {
	    Fits f = new Fits();
	    BasicHDU magnificationImageHDU = FitsFactory.HDUFactory(magnificationArray);
	    for (int i=0;i<keys.length;i++){
		magnificationImageHDU.addValue(keys[i], values[i], comments[i]);
	    }
	    BasicHDU shootingImageHDU = FitsFactory.HDUFactory(shootingArray);
	    FitsFactory.setUseAsciiTables(false);
	    Object data[] = new Object[]{starBag.getXArray(), starBag.getYArray(), starBag.getMassArray()};
	    BinaryTableHDU starTableHDU = (BinaryTableHDU)FitsFactory.HDUFactory(data);
	    starTableHDU.setColumnName(0,"Pos. X" , "X position in Einstein radii");
	    starTableHDU.setColumnName(1,"Pos. Y" , "X position in Einstein radii");
	    starTableHDU.setColumnName(2,"Mass" , "Star mass");
	    
//	    for (int i=0;i<starBag.size();i++){
//		starTableHDU.addRow(starBag.getPos(i));
//	    }

	    f.addHDU(magnificationImageHDU);
	    f.addHDU(shootingImageHDU);
	    f.addHDU(starTableHDU);

	    FileOutputStream fos = new FileOutputStream(filename);
	    BufferedDataOutputStream s = new BufferedDataOutputStream(fos);
	    f.write(s);
	} catch (FileNotFoundException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (FitsException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    public static void saveASCII(double[][] data, String filename){
	try {
	    BufferedWriter out = new BufferedWriter(new FileWriter("magPattern.txt"));
	    int nPixMap = data.length;
	    for (int j=0;j<nPixMap;j++){
		for (int i=0;i<nPixMap;i++){
		    out.write(Double.toString(data[j][i]) + "\n");
		}

	    }
	    out.close();
	} catch (IOException e) {
	}

    }
    public static String toHHmmss(double seconds){
	String result ="";
	if (seconds >86400){
	    int days =  (int)(seconds/86400);
	    result += days + "d:";
	    seconds-= days*86400;
	}
	int hours = (int)(seconds/3600);
	int minutes = (int)((seconds - hours*3600)/60);
	double sec = (seconds -hours*3600 -minutes*60); 
	result += hours + "h:" + minutes + "m:" + sec +"s";
	return result;
    }
    
    public static double [][] getArray(int sizeX, int sizeY){	
	double[][] result = new double[sizeY][sizeX];
	System.out.println("initializing array sizex: " + sizeX + ",sizey: " + sizeY);
	for (int j=0;j<sizeY;j++){
	    for (int i=0;i<sizeX;i++){
		result[j][i] = 0;
	    }
	}
	return result;

    }

}
